package com.xy.smartsms.facade;

import android.content.Context;

import com.xy.smartsms.db.carrierparam.BlackListManager;
import com.xy.smartsms.db.carrierparam.OnlineConfigManager;
import com.xy.smartsms.db.carrierparam.WhiteListManager;
import com.xy.smartsms.service.carrierparam.UpdateRunnableManager;
import com.xy.smartsms.util.Log;
import com.xy.smartsms.util.ThreadManager;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * Created by admin on 2017/2/24.
 */

public class CarrierParamFacade {
    private static final String TAG = CarrierParamFacade.class.getSimpleName();

    private Context mContext;
    /* 菜单开关 */
    public static final int FUNC_ENTERPRISE = 1 << 0;
    /* 企业资料开关 */
    public static final int FUNC_MENU = 1 << 1;
    /* 所有卡片开关 */
    public static final int FUNC_CARD = 1 << 2;
    /* 带情景的卡片开关 */
    public static final int FUNC_CARD_SCENE = 1 << 3;


    /* 融合方案 */
    public static final int TOP_SWITCH_MIX = 0;

    /* 小源 */
    public static final int TOP_SWITCH_XY = 1;

    /* 运营商 */
    public static final int TOP_SWITCH_OPERATOR = 2;


    private boolean isInitEnd = false;  //是否初始化完毕


    public void checkUpdate() {
        UpdateRunnableManager.getInstance(mContext).checkUpdate("");
    }

    /**
     * 根据功能类型，判断顶层开关
     *
     * @param funcType
     * @return if true, use bizport, otherwise use custom-defined
     */
    public int checkTopSwitch(int funcType) {
        int bitWiseIndex = 0;
        if (funcType == FUNC_ENTERPRISE) {
            bitWiseIndex = 0;
        } else if (funcType == FUNC_MENU) {
            bitWiseIndex = 3;
        } else if (funcType == FUNC_CARD) {
            bitWiseIndex = 6;
        }

        int topSwitch = OnlineConfigManager.getInstance().getTopSwitch();
        topSwitch = (topSwitch >> bitWiseIndex) & 7;
        switch (topSwitch) {
            case 1:
                topSwitch = TOP_SWITCH_XY;
                break;
            case 2:
                topSwitch = TOP_SWITCH_OPERATOR;
                break;
            case 0:
            default:
                topSwitch = TOP_SWITCH_MIX;
                break;
        }
        Log.d(TAG, "func " + funcType + " bitWiseIndex " + bitWiseIndex + " topSwitch " + topSwitch);
        return topSwitch;
    }

    /**
     * 预取，保证不在UI主线程里面访问database
     *
     * @param phone
     */
    public void prefetch(final String phone) {
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                BlackListManager.getInstance().preLoadData(phone);
                WhiteListManager.getInstance().preLoadData(phone);
                return null;
            }
        };
        FutureTask<Object> futureTask = new FutureTask<Object>(callable);
        ThreadManager.NUMBER_PRELOADDATA.execute(futureTask);
        try {
            futureTask.get(200, TimeUnit.MILLISECONDS);
        } catch (Throwable e) {
            Log.e(TAG, "prefetch", e);
        }

    }

    public boolean isParamReady(String phone) {
        if (!isInitEnd)
            return false;
        return BlackListManager.getInstance().isLoadSuccess(phone)
                && WhiteListManager.getInstance().isLoadSuccess(phone);
    }

    /**
     * 检查号码是否在白名单中；如果否，则用信析宝
     *
     * @param phone
     * @return
     */
    public boolean checkWhiteList(String phone) {
        boolean value = WhiteListManager.getInstance().checkNormal(phone);
        Log.v(TAG, "checkWhiteList: " + phone + "=" + value);
        return value;
    }

    /**
     * 检查号码是否是高级白名单，即运营商号码
     *
     * @param phone
     * @return
     */
    public boolean checkAdvancedWhiteList(String phone) {
        boolean value = WhiteListManager.getInstance().checkAdvanced(phone);
        Log.v(TAG, "checkAdvancedWhiteList: " + phone + "=" + value);
        return value;
    }

    /**
     * 获取高级白名单的名称，一般用于显示原文布局的标题
     *
     * @param phone
     * @return
     */
    public String getAdvancedWhiteListName(String phone) {
        String value = WhiteListManager.getInstance().getAdvancedName(phone);
        Log.v(TAG, "getAdvancedWhiteListName: " + phone + "=" + value);
        return value;
    }

    /**
     * 检查该号码的功能类型是否在黑名单上；如果是，则用信析宝
     *
     * @param phone
     * @param funcType
     * @return
     */
    public boolean checkBlackListSwitch(String phone, int funcType) {
        boolean value = BlackListManager.getInstance().checkSwitch(phone, funcType);
        Log.v(TAG, "checkBlackListSwitch: " + funcType + "=" + value);
        return value;
    }

    /**
     * 根据功能类型，判断当第三方没有结果时，是否开启bizport
     *
     * @param funcType
     * @return
     */
    public boolean checkOnResultNull(int funcType) {
        boolean value = OnlineConfigManager.getInstance().checkOnResultNull(funcType);
        Log.v(TAG, "checkOnResultNull: " + funcType + "=" + value);
        return value;
    }

    /**
     * 根据情景号（8位），判断是否需要屏蔽
     *
     * @param sceneId
     * @return
     */
    public boolean checkEscapeScene(String sceneId) {
        boolean value = OnlineConfigManager.getInstance().checkEscapeScene(sceneId);
        Log.v(TAG, "checkEscapeScene: " + sceneId + "=" + value);
        return value;
    }

    public void initData(Map<String, String> extend) {
        OnlineConfigManager.getInstance().initOnlineConfig(extend);
        WhiteListManager.getInstance().initDataToDb();
        BlackListManager.getInstance().initDataToDb();
        isInitEnd = true;
    }

    public void clearCache() {
        OnlineConfigManager.getInstance().clearCache();
        BlackListManager.getInstance().clearCache();
        WhiteListManager.getInstance().clearCache();
    }

    private static CarrierParamFacade sCarrierParamFacade = null;

    private CarrierParamFacade(Context context) {
        mContext = context;
        WhiteListManager.getInstance(mContext);
        BlackListManager.getInstance(mContext);
        OnlineConfigManager.getInstance(mContext);
    }

    public static CarrierParamFacade getInstance() {
        return sCarrierParamFacade;
    }

    public static CarrierParamFacade getInstance(Context context) {
        synchronized (CarrierParamFacade.class) {
            if (sCarrierParamFacade == null) {
                sCarrierParamFacade = new CarrierParamFacade(context.getApplicationContext());
            }
        }

        return sCarrierParamFacade;
    }

}
